﻿using System;
using System.Composition;
using System.Linq;
using System.Xml.Linq;
using Unread.Business.Data.Opml.Interfaces;
using Unread.Business.Data.Opml.Model;

namespace Unread.Business.Data.Opml
{
    /// <summary>
    /// Note: xml schema validation in WinRT differs from .NET or can't be done at all using the framework libraries
    /// </summary>
    [Export(typeof(IOpmlReader))]
    internal class OpmlReader : IOpmlReader 
    {
        public Root Read(string value)
        {
            if (value == null) throw new ArgumentNullException("value");

            var xml = XDocument.Parse(value);

            var root = new Root();

            LoadHead(xml, root);

            root.Body = new Body();
            root.Body.Outlines = (from outline in xml.Descendants("outline")
                                  select new Outline
                                  {
                                      Id = new Guid(outline.Attribute("id").GetValue(Guid.NewGuid().ToString())),
                                      Title = outline.Attribute("title").GetValue(),
                                      Subtitle = outline.Attribute("subtitle").GetValue(),
                                      Text = outline.Attribute("text").GetValue(),
                                      Type = outline.Attribute("type").GetValue(),
                                      XmlUrl = (!string.IsNullOrWhiteSpace(outline.Attribute("xmlUrl").GetValue()) ? new Uri(outline.Attribute("xmlUrl").GetValue()) : null),
                                      HtmlUrl = (!string.IsNullOrWhiteSpace(outline.Attribute("htmlUrl").GetValue()) ? new Uri(outline.Attribute("htmlUrl").GetValue()) : null),
                                      Image = (!string.IsNullOrWhiteSpace(outline.Attribute("image").GetValue()) ? new Uri(outline.Attribute("image").GetValue()) : null),
                                      LastRead = new DateTime(long.Parse(outline.Attribute("lastRead").GetValue(DateTime.MinValue.Ticks.ToString())))
                                  }).ToList();

            return root;
        }

        private void LoadHead(XDocument xml, Root root)
        {
            root.Head = new Head
            {
                Title = xml.Descendants("head").Single().Element("title").Value
            };
        }
    }
}
